<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面顶部显示滚动条进度</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .progress-box {
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            z-index: 1;
            height: 10px;
            background: rgba(0, 0, 0, .1);
        }
        .progress {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            background: deepskyblue;
        }
        main {
            height: 5000px;
        }
    </style>
</head>
<body>
    <div class="progress-box">
        <span class="progress"></span>
    </div>
    <main></main>

    <script>
        let progress = document.querySelector('.progress')

        document.onscroll = function() {
            let h_page = document.documentElement.scrollHeight || document.body.scrollHeight
            let h_viewport = document.documentElement.clientHeight || document.body.clientHeight // 视口高度
            let h_scrollable = h_page - h_viewport // 可滚动高度
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            let scroll_percentage = Math.floor((scrollTop / h_scrollable) * 100) // 当前滚动条滚动的百分比

            progress.style.width = `${scroll_percentage}%`
        }
    </script>
</body>
</html>
